package JDBC;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2022/8/25 21:52
 * 修改数据库中的记录
 */
public class JDBCUpdate {
    public static void main(String[] args) throws SQLException {
        //1.获取数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1234");
        //2.用户交互
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要修改数据的ID : ");
        int id = scanner.nextInt();
        System.out.println("请输入想要修改的名字");
        String name = scanner.next();
        //3.获取连接
        Connection connection = dataSource.getConnection();
        //4.操作数据库
        String sql= "update student set name = ?  where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);
        statement.setInt(2,id);
        System.out.println("statement : "+statement);
        //5.执行sql
        int ret = statement.executeUpdate();
        System.out.println(ret);
        //6.释放资源
        statement.close();
        connection.close();
    }
}
